package service

import (
	"fmt"
	commonFile "gin/common/file"
	commonLog "gin/common/log"
	//"log"
	//"fmt"
	"gin/common"
	"gin/common/constant"
	"gin/common/db/config"
	"strings"
	//commPage "gin/common/page"
	util2 "gin/common/util"
	genEntity "gin/generator/entity"
	"github.com/gin-gonic/gin"
)

//表名称  提取
var tableName = "gen_table"

//所有表字段提取
var sqlTitle = "table_id" + "," + "tb_name AS TbName" + "," + "table_comment" + "," + "sub_table_name" + "," + "sub_table_fk_name" + "," + "class_name" + "," + "tpl_category" + "," + "package_name" + "," + "module_name" + "," + "business_name" + "," + "function_name" + "," + "function_author" + "," + "gen_type" + "," + "gen_path" + "," + "options" + "," + "create_by" + "," + "create_time" + "," + "update_by" + "," + "update_time" + "," + "remark"

// QueryParams结构体，用于存储查询参数
type QueryParams struct {
	tableName    string
	tableComment string
}

/****
数据库表 信息等数据列表接口
2024-11-19 10:18
wangwei
***/
func GetGenList(c *gin.Context) {
	resultList := make([]*genEntity.GenTable, 0)

	genErr := config.GormDb.Model(&genEntity.GenTable{}).Table(tableName).Select(sqlTitle).Where("LOWER(1) = LOWER(?)", 1).Scan(&resultList).Error
	if genErr != nil {
		common.ReturnError(c, constant.ERRORCODE(), constant.ERRORMSG()+",错误详细信息为： "+util2.MapToJson(genErr), "", int64(len("")))
		panic("")
	}
	common.ReturnListSucess(c, constant.SUCCESSCODE(), constant.SUCCESSMSG(), resultList, int64(len(resultList)))
}

/****
数据库表 代码生成  导入表，弹框查询表
2024-11-19 10:36
wangwei
***/
func GetGenDbList(c *gin.Context) {
	//todo
}

/****
导入表
2024-11-19 17:12
wangwei
***/
func ImportTable(c *gin.Context) {
	//取传递的表名称
	tables := c.Query("tables")
	tablesArray := strings.Split(tables, ",")
	tableName := tablesArray[0]

	//重复导入检验
	genTable := genEntity.GenTable{}
	err1 := config.GormDb.Model(&genEntity.GenTable{}).Table("gen_table").Select(sqlTitle).Where(" tb_name = (?)", tableName).Scan(&genTable).Error
	if err1 != nil {
		common.ReturnError(c, constant.ERRORCODE(), "genbTable表数据信息查询失败,错误信息为："+util2.MapToJson(err1), "", int64(len("")))
		panic("")
	}

	if len(genTable.TbName) > 0 {
		common.ReturnError(c, constant.ERRORCODE(), "所选择的表已经导入gen_table表中，请勿重复操作", "", int64(len("")))
		panic("")
	}

	resultList := make([]genEntity.GenTable, 0)

	genErr := config.GormDb.Model(&genEntity.GenTable{}).Table("information_schema.tables as gen_table").
		Select("table_name as TbName"+","+"table_comment AS TableComment"+","+"create_time AS CreateTime"+","+"update_time AS UpdateTime").
		Where(" table_name NOT LIKE 'qrtz_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database()) ").
		Where("LOWER(table_name) = LOWER(?)", tableName).
		Scan(&resultList).Error
	if genErr != nil {
		common.ReturnError(c, constant.ERRORCODE(), constant.ERRORMSG()+",错误详细信息为： "+util2.MapToJson(genErr), "", int64(len("")))
		panic("")
	}
	importGenTable(c, resultList)
	common.ReturnSucess(c, constant.SUCCESSCODE(), constant.SUCCESSMSG(), resultList, int64(len(resultList)))
}

func importGenTable(c *gin.Context, tableList []genEntity.GenTable) {
	resultList := make([]*genEntity.GenTableColumn, 0)
	tables := c.Query("tables")
	//TODO 表数据导入  代码生成表   详细操作
	for _, table := range tableList {
		//	tableName := table.TableName
		//ClassName转首字母大写

		err := config.GormDb.Model(&genEntity.GenTable{}).Table("gen_table ").Create("TODO ").Error

		// 检查添加操作是否成功
		if err != nil {
			common.ReturnError(c, constant.ERRORCODE(), "操作失败", err, int64(len("")))
			panic("")
		} else {
			err := config.GormDb.Model(&genEntity.GenTableColumn{}).Table("information_schema.columns").
				Select("column_name as column_name", "(case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as is_required", "(case when column_key = 'PRI' then '1' else '0' end) as is_pk", "ordinal_position as sort", "column_comment as column_comment", "(case when extra = 'auto_increment' then '1' else '0' end) as is_increment", "column_type as column_type").
				Where(" table_schema = (select database()) and table_name = (?)", tables).
				Scan(&resultList).Error
			if err != nil {
				common.ReturnError(c, constant.ERRORCODE(), "登录用户数据库查询失败,错误信息为："+util2.MapToJson(err), "", int64(len("")))
				panic("")
			}
		}

		genTable := genEntity.GenTable{}
		err1 := config.GormDb.Model(&genEntity.GenTable{}).Table("gen_table").Select(sqlTitle).Where(" tb_name = (?)", table.TbName).Scan(&genTable).Error
		if err1 != nil {
			common.ReturnError(c, constant.ERRORCODE(), "genbTable表数据信息查询失败,错误信息为："+util2.MapToJson(err1), "", int64(len("")))
			panic("")
		}

		//新增每个列数据信息
		for _, column := range resultList {
		fmt.Println(column)
			//TODO
		}
	}
}

/***
选择的表后台代码生成，下载zip文件
TODO 目前只支持单表代码生成
2024-11-29 15:02
wangwei
*/
func BatchGenCode(c *gin.Context) {
	//取传递的表名称
	tables := c.Query("tables")
	tablesArray := strings.Split(tables, ",")
	//TODO 目前只支持单表代码生成
	tableName := tablesArray[0]

	//表检索校验
	genTable := genEntity.GenTable{}
	err1 := config.GormDb.Model(&genEntity.GenTable{}).Table("gen_table").Select(sqlTitle).Where(" tb_name = (?)", tableName).Scan(&genTable).Error
	if err1 != nil {
		common.ReturnError(c, constant.ERRORCODE(), "genbTable表数据信息查询失败,错误信息为："+util2.MapToJson(err1), "", int64(len("")))
		panic("")
	}

	//overwrite := global.GetConfigInstance().GetBool("gen.overwrite")
	//代码允许被生成覆盖
	//var overwrite bool = true
	//获取当前运行时目录
	//curDir, err := os.Getwd()

	//cur := genCon.GenTempPath()

//	var packagePath = cur + "business/"
	//todo 生成控制层api


	//todo 生成实体类
	//entity模板


	//todo 生成业务层代码
	//service模板

}

/*****
读取模板
2024-11-29 15:54
wangwei
*/
func LoadTemplate(templateName string, data interface{}) (string, error) {
	//todo
	return "", nil
}

func canGenIt(overwrite bool, file string) bool {
	logger := commonLog.InitLogger()
	if overwrite { //允许覆盖
		logger.Println("--------->您配置了 overwrite 开关的值为true，旧文件会被覆盖！！！！ ")
		return true
	} else {                         // 不允许覆盖
		if commonFile.Exists(file) { //文件已经存在，不允许重新生成
			logger.Println("=======> 文件已经存在，本次将不会生成新文件！！！！！！！！！！！！ ")
			return false
		} else { //文件不存在，允许重新生成
			return true
		}
	}
}

